﻿using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BreacherCreature.Components.Lights
{
    public class Flicker
    {
        #region Static Constants

        public static float DEFAULT_FLICKERING_TRANSPARENCY = .4f;
        static int DEFAULT_FLICKERING_DURATION = 5;
        static int DEFAULT_FLICKERING_COUNT = 4; // MUST BE EVEN TO CHANGE LIGHT STATE BETWEEN FLICKERS

        #endregion

        #region Protected Fields

        protected int _framesOn;
        protected int _framesOff;
        protected float _curFrame = 0;
        protected bool _isFlickering = false;
        protected int _flickeringCount = 0;

        #endregion

        #region Public Properties

        public int FlickerDuration
        {
            get;
            protected set;
        }

        public int FlickerCount
        {
            get;
            protected set;
        }

        public float FlickerTransparency
        {
            get;
            protected set;
        }

        public bool IsOn;
        public bool FullyOn
        {
            get { return IsOn && !_isFlickering; }
        }

        #endregion

        #region Constructors

        public Flicker(int framesOn, int framesOff, bool startOn)
        {
            _framesOn = framesOn;
            _framesOff = framesOff;
            IsOn = startOn;

            FlickerTransparency = DEFAULT_FLICKERING_TRANSPARENCY;
            FlickerCount = DEFAULT_FLICKERING_COUNT;
            FlickerDuration = DEFAULT_FLICKERING_DURATION;
        }
        public Flicker(int framesOn, int framesOff) : this(framesOn, framesOff, true) { }
        public Flicker(int framesBeforeSwitch) : this(framesBeforeSwitch, framesBeforeSwitch) { }

        #endregion

        #region Public Methods

        public virtual void Update(GameTime gameTime)
        {
            _curFrame += (float)gameTime.ElapsedGameTime.TotalSeconds * 60;
            if (_isFlickering)
            {
                if (_curFrame >= FlickerDuration)
                {
                    _curFrame = 0;
                    IsOn = !IsOn;
                    _flickeringCount++;
                    if (_flickeringCount == FlickerCount)
                    {
                        _isFlickering = false;
                        _flickeringCount = 0;
                    }
                }
            }
            else if (IsOn ? _curFrame >= _framesOn : _curFrame >= _framesOff)
            {
                IsOn = !IsOn;
                _isFlickering = true;
                _curFrame = 0;
            }
        }

        #endregion
    }
}
